<?php

namespace backend\controllers;

use Yii;
use backend\models\Menu;
use yii\data\ActiveDataProvider;
use backend\controllers\BaseController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use \yii\web\Response;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use backend\components\actions\ChangeValueAction;
use backend\module\yii2admin\components\Helper;
/**
 * MenuController implements the CRUD actions for Menu model.
 */
class MenuController extends BaseController {

    public $type;

    public function __construct($id, $module, $config = array()) {
        parent::__construct($id, $module, $config);
        $this->type = Yii::$app->request->get('typeid');
    }

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return ArrayHelper::merge(parent::behaviors(), [
            
        ]);
    }
    public function actions() {
        return ArrayHelper::merge(parent::actions(), [
            'change-value' => [
                'class' => ChangeValueAction::className(),
                'modelClass' => Menu::className(),
                'outputValue' => function($model, $attribute, $key, $index) {
                    return $model->$attribute;
                }
            ]
        ]);
    }
    /**
     * Lists all Menu models.
     * @return mixed
     */
    public function actionIndex() {
        $parentId = Yii::$app->request->get('parent');
        $menu = Menu::find()->where(['type' => $this->type]);
        $currParentMenu = Menu::findOne($parentId);
        if ($parentId) {
            $menu->andWhere(['parent' => $parentId]);
        } else {
            $menu->andWhere(['parent' => null]);
        }

        $dataProvider = new ActiveDataProvider([
            'query' => $menu
        ]);
        return $this->render('index', [
                    'type' => $this->type,
                    'parent' => $parentId,
                    'dataProvider' => $dataProvider,
                    'currParentMenu' => $currParentMenu,
        ]);
    }

    /**
     * Displays a single Menu model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id) {
        $request = Yii::$app->request;
        Yii::$app->response->format = Response::FORMAT_JSON;
        return [
            'title' => Yii::t('common', 'View'),
            'content' => $this->renderAjax('view', [
                'model' => $this->findModel($id),
            ]),
            'footer' => Html::button(Yii::t('common', 'Close'), ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
            Html::a(Yii::t('common', 'Edit'), ['update', 'id' => $id], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
        ];
    }

    /**
     * Creates a new Menu model.
     * For ajax request will return json object
     * and for non-ajax request if creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $request = Yii::$app->request;
        $model = new Menu();
        $model->order = 100;
        $model->type = $this->type;
        if ($request->isPost && $model->load($request->post()) && $model->save()) {
            Helper::invalidate();
            return $this->redirect(['index', 'typeid' => $model->type]);
        }
        return $this->render('create', [
            'type' => $this->type,
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing Menu model.
     * For ajax request will return json object
     * and for non-ajax request if update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id) {
        $request = Yii::$app->request;
        $model = $this->findModel($id);

        if ($request->isPost && $model->load($request->post()) && $model->save()) {
            Helper::invalidate();
            return $this->redirect(['index', 'typeid' => $model->type]);
        }
        return $this->render('update', [
                    'type' => $model->type,
                    'model' => $model,
        ]);
    }

    /**
     * Delete an existing Menu model.
     * For ajax request will return json object
     * and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id) {
        $request = Yii::$app->request;
        $this->findModel($id);
        $model = $this->findModel($id);
        $this->delUpload($model->icon);
        $model->delete();
        Helper::invalidate();
        Yii::$app->response->format = Response::FORMAT_JSON;
        return ['forceClose' => true, 'forceReload' => '#crud-datatable-pjax'];
    }

    /**
     * Delete multiple existing Menu model.
     * For ajax request will return json object
     * and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionBulkDelete() {
        $request = Yii::$app->request;
        $pks = explode(',', $request->post('pks')); // Array or selected records primary keys
        foreach ($pks as $pk) {
            $model = $this->findModel($pk);
            $this->delUpload($model->icon);
            $model->delete();
        }
        Helper::invalidate();
        Yii::$app->response->format = Response::FORMAT_JSON;
        return ['forceClose' => true, 'forceReload' => '#crud-datatable-pjax'];
    }

    /**
     * Finds the Menu model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Menu the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        if (($model = Menu::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    protected function delUpload($file){
        if($file){
            unlink(Yii::getAlias('@webroot').'/'.$file);
        }
    }
}
